﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalibrationSoftware
{
    //帧头校验算法HCS的类
    public class HCSCalculating
    {
        public ushort[] fcstab = new ushort[256];
        public const ushort PPPINITFCS16 = 0xffff;
        public const ushort PPPGOODFCS16 = 0xf0b8;

        // 构造函数，用于初始化fcstab表
        public HCSCalculating()
        {
            InitFcstab();
        }

        // 初始化fcstab表格，这里使用的是反转后的多项式PVAL: 0x8408
        private void InitFcstab()
        {
            for (int i = 0; i < 256; i++)
            {
                ushort fcs = (ushort)i;
                for (int j = 0; j < 8; j++)
                {
                    if ((fcs & 1) == 1)
                        fcs = (ushort)((fcs >> 1) ^ 0x8408);
                    else
                        fcs = (ushort)(fcs >> 1);
                }
                fcstab[i] = fcs;
            }
        }

        // 计算给定缓冲区的HCS值
        public ushort Pppfcs16(ushort fcs, byte[] cp)
        {
            for (int i = 0; i < cp.Length; i++)
                fcs = (ushort)((fcs >> 8) ^ fcstab[(fcs ^ cp[i]) & 0xff]);

            fcs ^= 0xffff; // 最后取反
            return fcs;
        }
    }
}
